from django.shortcuts import render,redirect,reverse
from django.views import View
from .forms import Changepass,InputAnswer
from django.contrib.auth.hashers import check_password,make_password
from .models import Students
from django.contrib import messages
from teacher_front.models import Subjects,ExamExtension,Exam,ExamPaper,StudentsAnswer
from django.utils.decorators import method_decorator
from student_front.students_decorator import check_login

@method_decorator(check_login,name='dispatch')
class Student_dashbord(View):
    def get(self,request):
        student = Students.objects.filter(number=request.session.get('user_id')).first()
        subjects = Subjects.objects.filter(student=student).all()
        infos = []
        for subject in subjects:
            info = {}
            name = subject.name
            college = subject.teacher.college
            teacher_name = subject.teacher.name
            creat_time = subject.creat_time
            exam_set = subject.exam_set
            info['name'] = name
            info['college'] = college
            info['teacher_name'] = teacher_name
            info['creat_time'] = creat_time
            info['exam_set'] = exam_set
            info['id'] = subject.id
            if Exam.objects.filter(subject=subject).exists():
                info['state'] = Exam.objects.filter(subject=subject).first().state
                info['total_score'] = Exam.objects.filter(subject=subject).first().total_score
            if exam_set:
                info['start_time'] = subject.exam.start_time
                info['end_time'] = subject.exam.end_time
                info['limit_time'] = subject.exam.time_limit
            infos.append(info)
        context = {
            'infos':infos,

        }

        return render(request,'students_dashbord.html',context=context)

def logout(request):
    request.session.clear()
    return redirect(reverse('index'))

@method_decorator(check_login,name='dispatch')
class Changepassword(View):
    def get(self,request):
        return render(request,'student_changepassword.html')
    def post(self,request):
        form = Changepass(request.POST)
        student_number = request.session.get('user_id')
        student = Students.objects.filter(number=student_number).first()
        if form.is_valid():
            password = form.cleaned_data.get('password')
            real_password = student.password
            new_password = form.cleaned_data.get('new_password')
            if check_password(password,real_password):
                student.password = make_password(new_password)
                student.save()
                return redirect(reverse('student:dashbord'))
            else:
                messages.info(request,'原始密码错误!')
                return redirect(reverse('student:changepass'))
        else:
            erros = form.get_error()
            for erro in erros:
                messages.info(request,erro)
            return redirect(reverse('student:changepass'))

@method_decorator(check_login,name='dispatch')
class StartExamIndex(View):
    def get(self,request,qid):
        subject = Subjects.objects.filter(id=qid).first()
        examsinglequestions = ExamExtension.objects.filter(exam__exam__subject=subject,type='single').all()
        exammultiplequestions = ExamExtension.objects.filter(exam__exam__subject=subject,type='multiple').all()
        examsubjectquestions = ExamExtension.objects.filter(exam__exam__subject=subject,type='subjective').all()
        downquestions = StudentsAnswer.objects.filter(subject=subject).values('examextension_id').all()
        havenid = []
        for downquestion in downquestions:
            havenid.append(downquestion['examextension_id'])
        context = {
            'questions_single':examsinglequestions,
            'questions_multiple':exammultiplequestions,
            'questions_subjective':examsubjectquestions,
            'subject_id':qid,
            'havenid':havenid,
        }
        return render(request,'stu_exambase.html',context=context)

@method_decorator(check_login,name='dispatch')
class StrartExam(View):
    def get(self,request,qid,oid):
        subject = Subjects.objects.filter(id=qid).first()
        examsinglequestions = ExamExtension.objects.filter(exam__exam__subject=subject, type='single').all()
        exammultiplequestions = ExamExtension.objects.filter(exam__exam__subject=subject, type='multiple').all()
        examsubjectquestions = ExamExtension.objects.filter(exam__exam__subject=subject, type='subjective').all()
        question = ExamExtension.objects.filter(pk=oid).first()
        downquestions = StudentsAnswer.objects.filter(subject=subject).values('examextension_id').all()
        havenid = []
        for downquestion in downquestions:
            havenid.append(downquestion['examextension_id'])
        if question.type == 'subjective':
            form = InputAnswer(instance=StudentsAnswer.objects.filter(examextension=question,subject=subject).first())
            context = {
                'questions_single': examsinglequestions,
                'questions_multiple': exammultiplequestions,
                'questions_subjective': examsubjectquestions,
                'question': question,
                'subject_id': qid,
                'question_id': oid,
                'havenid': havenid,
                'student_answer': StudentsAnswer.objects.filter(subject=subject, examextension=question).first(),
                'form':form
            }
        else:
            context = {
                'questions_single': examsinglequestions,
                'questions_multiple': exammultiplequestions,
                'questions_subjective': examsubjectquestions,
                'question':question,
                'subject_id':qid,
                'question_id':oid,
                'havenid': havenid,
                'student_answer': StudentsAnswer.objects.filter(subject=subject, examextension=question).first(),
            }
        return render(request,'stu_startexam.html',context=context)
    def post(self,request,qid,oid):

        subject = Subjects.objects.filter(pk=qid).first()
        examsinglequestions = ExamExtension.objects.filter(exam__exam__subject=subject, type='single').all()
        exammultiplequestions = ExamExtension.objects.filter(exam__exam__subject=subject, type='multiple').all()
        examsubjectquestions = ExamExtension.objects.filter(exam__exam__subject=subject, type='subjective').all()

        question = ExamExtension.objects.filter(pk=oid).first()
        if question.type == 'subjective':
            form = InputAnswer(request.POST)
            if form.is_valid():
                myanswer = form.cleaned_data.get('ans')
        else:
            myanswer = request.POST.get('myanswer').replace(' ','')
        downquestions = StudentsAnswer.objects.filter(subject=subject).values('examextension_id').all()
        havenid = []
        for downquestion in downquestions:
            havenid.append(downquestion['examextension_id'])


        if question.type == 'subjective':
            if StudentsAnswer.objects.filter(subject=subject, examextension=question).exists():
                StudentsAnswer.objects.filter(subject=subject, examextension=question).update(ans=myanswer)
            else:
                StudentsAnswer.objects.create(ans=myanswer, subject=subject, examextension=question)
            form = InputAnswer(instance=StudentsAnswer.objects.filter(examextension=question,subject=subject).first())
            context = {
                'questions_single': examsinglequestions,
                'questions_multiple': exammultiplequestions,
                'questions_subjective': examsubjectquestions,
                'question': question,
                'subject_id': qid,
                'question_id': oid,
                'havenid': havenid,
                'student_answer': StudentsAnswer.objects.filter(subject=subject, examextension=question).first(),
                'form':form
            }
        else:
            if StudentsAnswer.objects.filter(subject=subject, examextension=question).exists():
                if question.answer.lower() == myanswer.lower():
                    StudentsAnswer.objects.filter(subject=subject, examextension=question).update(ans=myanswer,total_score=question.value)
                else:
                    StudentsAnswer.objects.filter(subject=subject, examextension=question).update(ans=myanswer)
            else:
                if question.answer.lower() == myanswer.lower():
                    StudentsAnswer.objects.create(ans=myanswer, subject=subject, examextension=question,total_score=question.value)
                else:
                    StudentsAnswer.objects.create(ans=myanswer, subject=subject, examextension=question,)
            context = {
                'questions_single': examsinglequestions,
                'questions_multiple': exammultiplequestions,
                'questions_subjective': examsubjectquestions,
                'question': question,
                'subject_id': qid,
                'question_id': oid,
                'havenid': havenid,
                'student_answer': StudentsAnswer.objects.filter(subject=subject,examextension=question).first(),
            }
        return render(request, 'stu_startexam.html', context=context)

@check_login
def inputpaper(request,eid):
    exam = Exam.objects.filter(subject_id=eid).first()
    exam.state = True
    exam.save()
    return redirect(reverse('student:dashbord'))
